package net.lovesrc.allin.biz.huim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.zhouzhou.fastjava.http.HttpException;
import com.zhouzhou.fastjava.http.Requests;
import com.zhouzhou.fastjava.util.StringKit;
import com.zhouzhou.fastjava.util.ThreadKit;
import net.lovesrc.allin.biz.BaseService;
import net.lovesrc.allin.bo.User;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class HuiMService extends BaseService {

    public void processUserLike() {
        List<HuiMItem> newItems = findNewItems();
        List<String> hasLiked = Lists.newArrayList();
        List<String> userIds = jdbcTemplate.queryForList("select distinct userId from t_buy_kw", String.class);
        userIds.forEach(userId -> {
            List<HuiMItemUserLike> likes = Lists.newArrayList();
            List<JSONObject> kwRows = queryForRows(jdbcTemplate, "select * from t_buy_kw where userId = ?", userId);
            for (JSONObject row : kwRows) {
                String keyword = row.getString("keyword");
                for (HuiMItem item : newItems) {
                    if (hasLiked.contains(item.getId())) {
                        continue;
                    }
                    if (item.getTitle().contains(keyword)
                            || item.getContent().contains(keyword)) {
                        likes.add(
                                HuiMItemUserLike.builder()
                                        .keyword(keyword)
                                        .huiMItem(item)
                                        .build()
                        );
                        hasLiked.add(item.getId());
                    }
                }
            }
            onUserLikeItems(userId, likes);
        });
    }

    private void onUserLikeItems(String userId, List<HuiMItemUserLike> likes) {
        if (likes.isEmpty()) {
            return;
        }
        //t_buy_kw_match_record
        for (HuiMItemUserLike like : likes) {
            JSONObject row = new JSONObject()
                    .fluentPut("userId", userId)
                    .fluentPut("keyword", like.getKeyword())
                    .fluentPut("link", like.getHuiMItem().getUrl())
                    .fluentPut("title", like.getHuiMItem().getTitle())
                    .fluentPut("fromSite", "HUIM-" + like.getHuiMItem().getKind());
            insertRow(jdbcTemplate, "t_buy_kw_match_record", row);
        }

        User user = userService.getById(userId);

        //t_job_task
        StringBuilder stringBuilder = new StringBuilder();
        for (HuiMItemUserLike like : likes) {
            stringBuilder.append("<p>【" + like.getKeyword() + "】=========</p>");
            stringBuilder.append(String.format("<p><a href='%s'>%s</a></p>", like.getHuiMItem().getUrl(), like.getHuiMItem().getTitle()));
            stringBuilder.append("<p>----</p>");
            stringBuilder.append("<p>")
                    .append(StringUtils.left(like.getHuiMItem().getContent(), 50))
                    .append("</p>");
            stringBuilder.append("<br/>");
        }
        notificationService.email(user.getEmail(), Joiner.on("、").join(likes.stream().map(r -> r.getKeyword()).collect(Collectors.toSet())), stringBuilder.toString());
    }

    public List<HuiMItem> findNewItems() {
        List<HuiMItem> items = this.fetchItems();
        List<HuiMItem> newItems = items.stream()
                .filter(r -> !redisTemplate.hasKey("huim:" + r.getId()))
                .collect(Collectors.toList());
        newItems.forEach(r -> redisTemplate.opsForValue().set("huim:" + r.getId(), JSON.toJSONString(r), 5, TimeUnit.DAYS));
        return newItems;
    }

    private List<HuiMItem> fetchItems() {
        try {
            return doFetchItems();
        } catch (HttpException e) {
            logger.error("fetch items error", e);
            return Lists.newArrayList();
        }
    }

    private List<HuiMItem> doFetchItems() {

        List<HuiMItem> items = Lists.newArrayList();
        // kuaibao
        {
            String url = "http://www.huim.com/kuaibao/";
            String html = Requests.get(url)
                    .printResText(false)
                    .executeUtilReturn200()
                    .asText();
            Document root = Jsoup.parse(html);
            Elements itemDoms = root.select("#ulmain > .zhi_list");
            List<HuiMItem> pageItems = itemDoms.stream()
                    .map(this::doParseKuaiBaoItem)
                    .collect(Collectors.toList());
            items.addAll(pageItems);
        }
        ThreadKit.sleepSeconds(1);
        {
            String url = "http://www.huim.com/";
            String html = Requests.get(url)
                    .printResText(false)
                    .executeUtilReturn200()
                    .asText();
            Document root = Jsoup.parse(html);
            Elements itemDoms = root.select("#content-item > .get_coupon");
            List<HuiMItem> pageItems = itemDoms.stream()
                    .map(this::doParseHomeItem)
                    .collect(Collectors.toList());
            items.addAll(pageItems);
        }
        return items;
    }

    private HuiMItem doParseHomeItem(Element itemDom) {
        Element goToLink = itemDom.selectFirst(".quan_item_con .quan_item_tit a");
        String uri = goToLink.attr("href");
        String title = goToLink.text();
        String content = itemDom.selectFirst(".quan_item_con .quan_desc").text();
        String id = StringKit.extract(itemDom.attr("onclick"), "TrackClick\\('1-(\\d+)'\\)");
        return HuiMItem.builder()
                .id(id)
                .kind("QUAN")
                .url(uri)
                .title(title)
                .content(content)
                .build();
    }

    private HuiMItem doParseKuaiBaoItem(Element itemDom) {
        String uri = itemDom.select(".list_tit a").attr("href");
        String title = itemDom.select(".list_tit").text();
        String content = itemDom.select(".list_doc").text();
        String id = StringKit.extract(uri, "/detail/(\\d+)\\.html");
        return HuiMItem.builder()
                .id(id)
                .kind("KUAIBAO")
                .url("http://www.huim.com" + uri)
                .title(title)
                .content(content)
                .build();
    }

}
